<template>
  <a-list style="width: 370px" size="small">
    <template #header>
      <a-button size="mini" type="primary" @click="handleAdd">
        新增一条
      </a-button>
    </template>
    <a-list-item v-for="(item, idx) of value" :key="idx">
      <a-space>
        <a-input
          v-model="value[idx]"
          style="width: 300px"
          placeholder="请输入"
          @input="(val) => onInput(idx, val)"
        ></a-input>
        <a-button
          v-if="value.length > 1"
          type="text"
          size="small"
          shape="circle"
          @click="handleDel(idx)"
        >
          <icon-delete />
        </a-button>
      </a-space>
    </a-list-item>
  </a-list>
</template>

<script lang="ts" setup>
  import { ref, withDefaults, defineEmits, defineProps, watch } from 'vue';

  // TODO 待定
  interface Props {
    modelValue: string[];
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: () => {
      return [];
    },
  });
  const emit = defineEmits(['update:modelValue']);

  const value = ref<string[]>([]);

  const onInput = (idx: number, val: string) => {
    const list = JSON.parse(JSON.stringify(value.value));
    list[idx] = val;
    emit('update:modelValue', list);
  };

  const handleAdd = () => {
    const list = JSON.parse(JSON.stringify(value.value));
    list.push('');
    emit('update:modelValue', list);
  };

  const handleDel = (idx) => {
    const list = JSON.parse(JSON.stringify(value.value));
    list.splice(idx, 1);
    emit('update:modelValue', list);
  };

  watch(
    () => props.modelValue,
    (newVal) => {
      value.value = newVal || [];
    },
    {
      immediate: true,
    }
  );
</script>

<style lang="less" scoped></style>
